<template>
    <el-form ref="articleForm" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm" status-icon>

        <el-form-item label="标题" prop="article_title">
            <el-input v-model="ruleForm.article_title" />
        </el-form-item>

        <el-form-item label="作者" prop="article_author">
            <el-input v-model="ruleForm.article_author" />
        </el-form-item>

        <el-form-item label="分类" prop="article_navigate">
            <el-input v-model="ruleForm.article_navigate" />
        </el-form-item>

        <el-form-item label="时间" required>
            <el-col :span="11">
                <el-form-item prop="article_create_time">
                    <el-date-picker v-model="ruleForm.article_create_time" type="date" label="" placeholder="开始"
                        style="width: 100%" disabled />
                </el-form-item>
            </el-col>
            <el-col class="text-center" :span="2">
                <span class="text-gray-500"></span>
            </el-col>
        </el-form-item>

        <el-form-item label="文章介绍" prop="article_text">
            <el-input v-model="ruleForm.article_text" type="textarea" />
        </el-form-item>

        <el-form-item>
            <WangEditor @handleBlurxxxx="addWangEditorContent" :contentxxx="content"></WangEditor>
        </el-form-item>

        <el-form-item>
            <el-upload class="upload-demo" drag :on-change="handleImgChange" accept="image/*" :auto-upload="false"
                style="width:50%">
                <el-icon class="el-icon--upload">
                    <upload-filled />
                </el-icon>
                <div class="el-upload__text">
                    <div>设置文章封面</div>
                    <div>点击上传</div>
                </div>
                <template #tip>
                    <div class="el-upload__tip"></div>
                </template>
            </el-upload>
        </el-form-item>

        <el-form-item label="标签" prop="article_tags">
            <el-input v-model="ruleForm.article_tags" placeholder="标签1,标签2,标签3" />
        </el-form-item>

        <el-form-item>
            <el-button type="primary" @click="addArticle(articleForm)">发布文章</el-button>
            <el-button @click="resetForm(articleForm)">重置</el-button>
        </el-form-item>

    </el-form>
</template>
<script lang="ts" setup>
// 导入富文本框组件
import WangEditor from '../../components/WangEditor.vue'
// 引入处理html字符串的插件
import {escape, unescape}  from 'html-escaper'
// 导入格式化时间插件
import moment from "moment";
// 导入消息提示框
import { ElMessage } from 'element-plus';
// 导入定义数据的方法
import { ref, reactive, onMounted } from 'vue';
// 导入表单组件对象
import type { FormInstance, FormRules } from 'element-plus';
// 导入上传文件图标
import { UploadFilled } from '@element-plus/icons-vue';
// 导入相关接口
import { articleAddApi, articleUpdateApi, articleDetailApi } from '../../http/request';
// 导入创建路由方法
import { useRouter } from 'vue-router';
// 定义路由
const $router = useRouter();
// 定义变量
let article_id: any = ref("");
// 获取token
let token: any = localStorage.getItem('token');
// 定义文章表单实例
const articleForm = ref<FormInstance>();
// 定义对象记录表单提交的数据
const ruleForm = reactive({
    article_title: '', // 文章标题
    article_author: '', // 文章作者
    article_create_time: '',// 文章创建时间
    article_text: '',// 文章介绍
    article_content: '',// 文章内容
    article_tags: '',// 文章标签
    article_navigate:'分类', //分类
    file: ''// 文章封面
})
// 设置表单约束
const rules = reactive<FormRules>({
    // 标题
    article_title: [
        { required: true, message: '请输入文章名称', trigger: 'blur' }
    ],
    // 链接
    article_author: [
        {
            required: true,
            message: '请输入文章链接地址',
            trigger: 'change',
        },
    ],
    // 创建时间
    article_create_time: [
        {
            type: 'date',
            required: true,
            message: '请选择一个时间',
            trigger: 'change',
        },
    ],
    // 描述文字
    article_text: [
        { required: true, message: '请输入文章描述', trigger: 'blur' },
    ],
    // 描述文字
    article_tags: [
        { required: true, message: '请输入标签', trigger: 'blur' },
    ],
})
// 设置时间（默认）
ruleForm.article_create_time = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');

// 获取富文本框的内容
const addWangEditorContent = (result: any) => {
    // console.log("富文本框的内容:", result)
    // 记录富文本输入框（整合html的标点符号）
    // console.log('xxx--->:',escape(result.content))
    ruleForm.article_content = escape(result.content);
}
// 定义变量传值给富文本框
let content = ref("")
// 编写添加文章方法
const addArticle = async (formObj: FormInstance | undefined) => {
    if (!formObj) return
    await formObj.validate(async (valid, fields) => {
        if (valid) {
            let { article_title, article_author, article_tags, article_text, file ,article_navigate,article_content} = ruleForm;
            let formData = new FormData();
            formData.append("token", token);
            formData.append('article_author', article_author);
            formData.append('article_tags', article_tags);
            formData.append('article_navigate', article_navigate);
            formData.append('article_content', article_content);
            // formData.append('article_create_time', moment(new Date(article_create_time)).format('YYYY-MM-DD HH:mm:ss'))
            formData.append('article_text', article_text);
            formData.append('photo', file);
            formData.append('article_title', article_title);
            formData.append("fileType", "IMAGE");
            // console.log("article_id:",article_id)
            if (article_id.value) {
                // 修改文章
                formData.append("article_id", article_id.value)
                articleUpdateApi(formData)
                    .then(
                        (data: any) => {
                            // console.log('--->:',data);
                            if (data.code == 200) {
                                // 重置表单
                                formObj.resetFields();
                                // 延迟300ms跳转页面
                                let timeout = setTimeout(() => {
                                    $router.push({ path: '/article/list' });
                                    clearTimeout(timeout);
                                }, 300)
                                // 提示
                                ElMessage({
                                    message: data.msg,
                                    type: 'success',
                                });
                            } else {
                                // 提示
                                ElMessage({
                                    message: data.msg,
                                    type: 'warning',
                                });
                            }
                        }
                    ).catch(
                        err => {
                            console.log(err)
                        }
                    )
            } else {
                // 发布文章
                articleAddApi(formData)
                    .then(
                        (data: any) => {
                            // console.log('4.0',data)
                            if (data.code == 200) {
                                // 重置表单
                                formObj.resetFields();
                                // 延迟300ms跳转页面
                                let timeout = setTimeout(() => {
                                    $router.push({ path: '/article/list' });
                                    clearTimeout(timeout);
                                }, 300)
                                // 提示
                                ElMessage({
                                    message: data.msg,
                                    type: 'success',
                                });
                            } else {
                                // 提示
                                ElMessage({
                                    message: data.msg,
                                    type: 'warning',
                                });
                            }
                        }
                    )
                    .catch(
                        err => {
                            console.log(err)
                        }
                    )
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}
// 编写重置文章方法
const resetForm = (formObj: FormInstance | undefined) => {
    if (!formObj) return
    formObj.resetFields()
}
// 获取上传文件行为
const handleImgChange = (event: any) => {
    let file = event['raw'];
    if (file) {
        ruleForm.file = file
    } else {
        ElMessage("请选择文章封面图片。")
    }
}
// 获取文章详情
const Detailarticle = (article_id: any) => {
    // 获取文章详情
    articleDetailApi({ token, article_id: article_id.value })
        .then(
            (data: any) => {
                if (data.code == 200) {
                    let { article_title, article_author, article_create_time, article_text, article_content,article_tags ,article_navigate} = data.result[0];
                    ruleForm.article_title = article_title;
                    ruleForm.article_author = article_author;
                    ruleForm.article_create_time = article_create_time;
                    ruleForm.article_navigate = article_navigate;
                    ruleForm.article_text = article_text;
                    ruleForm.article_content = unescape(article_content);
                    ruleForm.article_tags = article_tags;
                    content.value = unescape(article_content);
                    console.log('xxx->',unescape(article_content));
                }
            }
        )
        .catch(
            error => {
                console.log(error);
            }
        )
}
// 调用挂载钩子函数
onMounted(() => {
    // 初始化文章
    // console.log(article_id)
    if ($router && $router.currentRoute.value.query) {
        article_id.value = $router.currentRoute.value.query.article_id
        if (article_id.value) {
            Detailarticle(article_id)
        }
    }

})
</script>
<style lang="scss">
.el-upload-dragger {
    margin-bottom: 20px;
    padding-top: 0px;
    padding-bottom: 0px;

    div {
        padding: 0 !important;
        margin: 0 !important;
    }
}

.demo-ruleForm {
    ::v-deep .el-picker-panel__body {
        z-index: 100000000000;
        background-color: #ccc;
    }
}
</style>